package com.yifeng.repo.controller.postman.web;

import com.gomcarter.frameworks.base.common.RequestUtils;
import com.gomcarter.frameworks.base.json.JsonData;
import com.gomcarter.frameworks.base.json.JsonError;
import com.yifeng.repo.base.utils.converter.JacksonHelper;
import com.yifeng.repo.controller.postman.work.PostmanManager;
import com.yifeng.repo.controller.postman.work.dto.HttpRequestParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created by daibing on 2023/5/23.
 */
@Slf4j
public class PostmanServlet extends HttpServlet {
    private final PostmanManager postmanManager;

    public PostmanServlet(PostmanManager postmanManager) {
        this.postmanManager = postmanManager;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpRequestParam callbackParam = new HttpRequestParam();
        callbackParam.setMethod(HttpMethod.resolve(req.getMethod()));
        callbackParam.setContentType(req.getContentType());
        callbackParam.setHeader(RequestUtils.headerMap(req));
        callbackParam.setBody(RequestUtils.body(req.getReader()));
        callbackParam.setUri(req.getRequestURI());
        try {
            String msg = postmanManager.doCallbackWork(callbackParam);
            this.doWrite(resp, msg);
        } catch (Throwable t) {
            log.error("callback handle error: ", t);
            this.doError(resp, HttpServletResponse.SC_BAD_REQUEST, t.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void doError(HttpServletResponse resp, int code, String msg) throws IOException {
        JsonError jsonError = new JsonError(msg, code);
        resp.setStatus(code);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        resp.setHeader("Cache-Control", "no-cache");
        resp.getOutputStream().write(JacksonHelper.toJson(jsonError).getBytes(StandardCharsets.UTF_8));
    }

    private void doWrite(HttpServletResponse resp, Object obj) throws IOException {
        JsonData jsonData = new JsonData(obj);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        resp.setHeader("Cache-Control", "no-cache");
        resp.getOutputStream().write(JacksonHelper.toJson(jsonData).getBytes(StandardCharsets.UTF_8));
    }

}
